﻿#region Copyright RenGuiYou. All rights reserved.
//=====================================================
// NeatlyFrameWork
// Author:      RenGuiyou
// Feedback: 	mailto:750539605@qq.com
//=====================================================
#endregion
using Cysharp.Threading.Tasks;
using Neatly.Load.Pool;
using Neatly.Module;
using UnityEngine;

namespace Neatly.Load.Manager
{
    public class SoundLoadManager : Singleton<SoundLoadManager>
    {
        private LoadModule m_LoadModule;
        private SoundPool m_SoundPool;
        private AssetBundle m_VoiceBundle;

        public async UniTask Init(LoadModule loadModule)
        {
            m_LoadModule = loadModule;
            m_SoundPool = new SoundPool();
            if (!NeatlyConfig.AssetBundleEnable) return;
            var loader = await m_LoadModule.LoadAssetBundleDirect(NeatlyConfig.SOUND_PACKAGE, true, true);
            var soundBundle = loader.ResultObject as AssetBundle;
            var audioClip = soundBundle.LoadAllAssets<AudioClip>();
            foreach (var clip in audioClip)
            {
                m_SoundPool.Add(clip.name, clip);
            }
        }

        public async UniTask<AudioClip> LoadMusic(string fileName)
        {
            if (NeatlyConfig.AssetBundleEnable)
            {
                var loader = await m_LoadModule.LoadAssetBundleDirect($"music_{fileName}", true, true);
                return loader.LoadAsset<AudioClip>(fileName);
            }
            string path = $"data/{NeatlyConfig.MUSIC_PACKAGE}/{fileName}{NeatlyConfig.SUFFIX_MUSIC}";
            return await m_LoadModule.LoadAssetFileSync<AudioClip>(path);
        }

        public async UniTask<AudioClip> LoadSound(string fileName)
        {
            if (NeatlyConfig.AssetBundleEnable)
            {
                return m_SoundPool.Get(fileName);
            }
            string path = $"data/{NeatlyConfig.SOUND_PACKAGE}/{fileName}{NeatlyConfig.SUFFIX_SOUND}";
            return await m_LoadModule.LoadAssetFileSync<AudioClip>(path);
        }

        public async UniTask<AudioClip> LoadVoice(string fileName)
        {
            if (!NeatlyConfig.AssetBundleEnable)
            {
                string path = $"data/{NeatlyConfig.VOICE_PACKAGE}/{fileName}{NeatlyConfig.SUFFIX_SOUND}";
                return await m_LoadModule.LoadAssetFileSync<AudioClip>(path);
            }
            if (!m_VoiceBundle)
            {
                var loader = await m_LoadModule.LoadAssetBundleDirect(NeatlyConfig.VOICE_PACKAGE, true, true);
                m_VoiceBundle = loader.ResultObject as AssetBundle;
            }
            return m_VoiceBundle.LoadAsset<AudioClip>(fileName);
        }
    }
}